import { reactive, UnwrapRef, toRefs } from "vue";

export interface ReactiveState<T> {
	// 原始数据
	data: UnwrapRef<T>;
	// 加载状态
	loading: boolean;
	// 错误状态
	error: Error | null;
	// 是否已初始化
	initialized: boolean;
}

// @ts-ignore
export interface ReactiveActions<T> {
	// 重置数据
	reset: () => void;
	// 设置加载状态
	setLoading: (value: boolean) => void;
	// 设置错误状态
	setError: (error: Error | null) => void;
}

export type ReactiveReturn<T> = {
	state: {
		data: UnwrapRef<T>;
		loading: boolean;
		error: Error | null;
		initialized: boolean;
	};
	actions: ReactiveActions<T>;
};

/**
 * 响应式状态管理 Hook
 * @param initialData 初始数据
 * @returns 包含状态和操作方法的对象
 */
export function useReactive<T>(initialData: T): ReactiveReturn<T> {
	// 创建响应式状态
	const state = reactive<ReactiveState<T>>({
		data: initialData as UnwrapRef<T>,
		loading: false,
		error: null,
		initialized: true,
	});

	// 创建操作方法
	const actions: ReactiveActions<T> = {
		// 重置数据
		reset: () => {
			// @ts-ignore
			state.data = initialData as UnwrapRef<T>;
			state.error = null;
			state.initialized = false;
		},

		// 设置加载状态
		setLoading: (value: boolean) => {
			state.loading = value;
		},

		// 设置错误状态
		setError: (error: Error | null) => {
			state.error = error;
		},
	};

	return {
		state: toRefs(state) as unknown as ReactiveReturn<T>['state'],
		actions,
	};
}
